<?php
namespace App\Http\Controllers\Api;

use App\Model\CouponListTable;
use App\Model\FieldTable;
use App\Model\InviteTeamTable;
use App\Model\OrderTable;
use App\Model\TimeBlockTable;
use App\Model\UserLevelSetTable;
use App\Model\UserTable;
use App\Repository\Common\ConstTable;
use App\Repository\BaseController\ApiController;
use App\Repository\Sys\JsonRespose;
use App\Repository\Sys\Str;
use App\Repository\Sys\Sys;
use EasyWeChat\Foundation\Application;
use EasyWeChat\User\User;
use Illuminate\Support\Facades\Log;

/**
 *
 * wap服务 无需授权访问的接口
 * Class WapController
 * @package App\Http\Controllers\Api
 */
class WapController extends ApiController
{

    public function getOauthCallback()
    {
        $app = new Application(config('app.weixin_options'));
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();

        session(['wechat_user' => $user->toArray()]);

        $targetUrl = empty(session('target_url')) ? '/' : session('target_url');
        header('location:' . $targetUrl); // 跳转到 user/profile


    }


    //支付回调接口
    public function postPayCallback()
    {
        Log::info("支付回调开始");

        $app = new Application(config('app.weixin_options'));
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            Log::info("回掉返回的数据：" . json_encode($notify));

            //$notify=json_decode('{"appid":"wxe222b512aca754b8","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1496871142","nonce_str":"5a93ae094119e","openid":"oYHoJ0901JIHvvfn7MhpKquS7w_E","out_trade_no":"ORDER_216","result_code":"SUCCESS","return_code":"SUCCESS","sign":"81078A22353157B607F864E8852FB57A","time_end":"20180226145001","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000077201802268691722107"}');


            if ($notify->result_code == 'SUCCESS') {
                // 你的逻辑
                //$notify->total_fee 或者 $notify['total_fee']。
                //result_code == ‘SUCCESS’

                $order_sn_str = explode('_', $notify->out_trade_no);
                $order_sn = $order_sn_str[1];

                $order = OrderTable::ORM()->where('order_id', $order_sn)->first();

                if (!$order) {
                    Log::error('订单不存在');
                    return false;
                }
                if ($order->pay_type != 1) {
                    Log::error('订单已经支付');
                    return false;
                }
                if (bcdiv($notify->total_fee, 100, 2) != $order->money) {
                    Log::error('支付金额错误');
                    return false;
                }

                $data = [
                    'weixin_sn' => $notify->transaction_id,
                    'pay_type' => 2
                ];

                if ($order->order_type == 2) {
                    $data['status'] = 2;
                }
                $res = OrderTable::ORM()->where('order_id', $order_sn)->update($data);
                if (!$res) {
                    Log::error('更新订单失败');
                    return false;
                }


                //别人先定了 走退款

                if ($order->order_type == 3) {
                    //是否约了 相同时间场定
                    $res = OrderTable::ORM()->where('order_type', 1)->where('pay_type', 2)->where('status', 1)->where('field_id',$order->field_id)
                        ->where('start_time',$order->start_time)->where('end_time',$order->end_time)->where('day_time',$order->day_time)->first();
                    if($res){
                        OrderTable::orderBack($res->order_id);
                    }
                    
                }


                //  写入积分  并更新会员等级

                $user = UserTable::ORM()->where('id', $order->uid)->first();
                $integral = $user->integral + (int)$order->money;
                UserLevelSetTable::updateLevel($order->uid, $integral);  //更新会员等级与积分


                if ($order->order_type != 1) { // 处理 发布约战 =>支付 别人先定了 走退款 （约战不锁定 其他才锁定）
//                    $day = strtotime(date('Y-m-d', $order->start_time));
                    $start_time =$order->start_time;


                    //两处联动
                    $time_block = TimeBlockTable::ORM()->where('field_id', $order->field_id)->where('day', $order->day_time)->where('start_time', $start_time)->first();
                    if ($time_block) {
                        $s = TimeBlockTable::ORM()->where('id', $time_block->id)->update([
                            'order_id' => $order_sn,
                            'price' => $order->field_price,
                        ]);
                        Log::info('更新订单时间1');
                    } else {
                        $s = TimeBlockTable::ORM()->insert([
                            'day' => $order->day_time,
                            'start_time' => $start_time,
                            'end_time' => Str::timeTotime(date('H:i', $order->end_time)),

                            'field_id' => $order->field_id,
                            'order_id' => $order_sn,
                        ]);
                        Log::info('更新订单时间2');
                    }
                    if (!$s) {
                        Log::error('更新订单时间表时出错');
                    }
                }

                if ($order->order_type == 1) {
                    $s = InviteTeamTable::ORM()->where('id', $order->object_id)->update(['status' => 2]); //约战中

                    //  约战成功
                    $phone=$user->phone;
                    $field_info=FieldTable::getFieldInfo($order->field_id);
                    $str="{$field_info['storefront_name']}".date('Y年m月d日',$order->day_time).date(' H点-',$order->start_time).date('H点',$order->end_time)." ".$field_info['type_text']. " {$field_info['number']}"; //   //汉口江滩2018年03月17日 09：00-11：00  5V5  1

                    //  订场成功
                    Sys::SendMessage(4072558,[$phone],[$str]);

                }
                if ($order->order_type == 2) {
                    $s = InviteTeamTable::ORM()->where('id', $order->object_id)->update(['status' => 3]); //约战成功
                    //更新主队order
                    OrderTable::ORM()->where('order_type', 1)->where('object_id', $order->object_id)->update(['status' => 2]);  // ing

                    $master_res= OrderTable::ORM()->where('order_type', 1)->where('object_id', $order->object_id)->first();
                    $master_phone=UserTable::ORM()->where('id',$master_res->uid)->first()->phone;
                    $field_info=FieldTable::getFieldInfo($master_res->field_id);
                    $str="{$field_info['storefront_name']}".date('Y年m月d日',$master_res->day_time).date(' H点-',$master_res->start_time).date('H点',$master_res->end_time)." ".$field_info['type_text']. " {$field_info['number']}"; //   //汉口江滩2018年03月17日 09：00-11：00  5V5  1
                    // 两条短 匹配成功  主队
                    Sys::SendMessage(4072563,[$master_phone],[$str]);



                    $phone=$user->phone;
                    $field_info=FieldTable::getFieldInfo($order->field_id);
                    $str="{$field_info['storefront_name']}".date('Y年m月d日',$order->day_time).date(' H点-',$order->start_time).date('H点',$order->end_time)." ".$field_info['type_text']. " {$field_info['number']}"; //   //汉口江滩2018年03月17日 09：00-11：00  5V5  1

                    // 两条短   应战成功 客队
                    Sys::SendMessage(3982516,[$phone],[$str]);

                }

                if($order->order_type == 3){

                    $phone=$user->phone;
                    $field_info=FieldTable::getFieldInfo($order->field_id);
                    $str="{$field_info['storefront_name']}".date('Y年m月d日',$order->day_time).date(' H点-',$order->start_time).date('H点',$order->end_time)." ".$field_info['type_text']. " {$field_info['number']}"; //   //汉口江滩2018年03月17日 09：00-11：00  5V5  1

                    //  订场成功
                     Sys::SendMessage(4052561,[$phone],[$str]);
                }



                if (!$s) {
                    Log::error('更新约战表失败1');
                }
                if ($order->coupon_id) {
                    $coupon = CouponListTable::ORM()->where('id', $order->coupon_id)->first();
                    if ($coupon->number > 1) {
                        CouponListTable::ORM()->where('id', $order->coupon_id)->decrement('number', -1);
                    } else {
                        CouponListTable::ORM()->where('id', $order->coupon_id)->delete();
                    }
                }

                Log::info('回掉成功');
                return true;
            }
            Log::error('回掉状态不是succeed');
            return false;
        });
        $response->send();
        die;


    }

    //微信支付成功通知模板
    static public function weixinNotice($openid, $templateId, $order_id)
    {

        /*
         * 模板
您好，您已消费成功。

消费金额：{{pay.DATA}}
消费地址：{{address.DATA}}
消费时间：{{time.DATA}}
{{remark.DATA}}
        */
        $order_info = Pay::OrderInfo($order_id);
        $app = new Application(Common::getWeixinOptions());
        $notice = $app->notice;
        $userId = $openid;
        $url = ServiceManager::getConfig('url') . '/web/user/consumptiondetailed?order_id=' . $order_id;
        $data = array(
            "pay" => "{$order_info['money']}元",
            "address" => "异吧",
            "time" => date('Y年m月d日 H:i'),
            "remark" => "欢迎下次光临！",
        );


        try {
            $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
        } catch (\Exception $e) {
            Logger::writeLog("微信支付推送消息失败,openid: {$openid},错误消息" . $e->getMessage());
            return false;
        }
        Logger::writeLog("微信支付成功推送消息" . $result);
        return true;
        // var_dump($result);
// {
//      "errcode":0,
//      "errmsg":"ok",
//      "msgid":200228332
//  }


    }


    //测试
    public function getPayCallback()
    {
        Log::error('支付回调错误');
    }

}
